from datetime import datetime
from app import db

class Objective(db.Model):
    __tablename__ = 'objectives'

    id = db.Column(db.Integer, primary_key=True)
    title = db.Column(db.String(200), nullable=False)
    description = db.Column(db.Text)
    owner_id = db.Column(db.Integer, db.ForeignKey('users.id'), nullable=False)
    level = db.Column(db.String(20), nullable=False)  # company, department, individual
    type = db.Column(db.String(20), nullable=False)  # operational, strategic, development
    parent_id = db.Column(db.Integer, db.ForeignKey('objectives.id'), nullable=True)
    start_date = db.Column(db.Date, nullable=False)
    end_date = db.Column(db.Date, nullable=False)
    progress = db.Column(db.Float, default=0.0)
    status = db.Column(db.String(20), default='active')  # active, completed, cancelled
    created_at = db.Column(db.DateTime, default=datetime.utcnow)
    updated_at = db.Column(db.DateTime, default=datetime.utcnow, onupdate=datetime.utcnow)

    # 关系
    key_results = db.relationship('KeyResult', backref='objective', lazy='dynamic', cascade='all, delete-orphan')
    children = db.relationship('Objective', backref=db.backref('parent', remote_side=[id]), lazy='dynamic')
    project_links = db.relationship('ProjectObjectiveLink', backref='objective', lazy='dynamic', cascade='all, delete-orphan')
    progress_updates = db.relationship('ProgressUpdate', backref='objective', lazy='dynamic')

    def calculate_progress(self):
        """
        计算目标进度
        - 如果是部门目标且有下属认领的子目标，则根据子目标的平均进度计算
        - 否则根据关键成果计算
        - 如果都没有，保持当前进度
        """
        # 1. 优先：如果是部门目标，检查是否有下属认领的子目标
        if self.level == 'department':
            child_objectives = self.children.filter_by(status='active').all()
            if child_objectives:
                # 根据下属目标的平均进度计算
                total_progress = sum(child.progress for child in child_objectives)
                self.progress = round(total_progress / len(child_objectives), 2)
                return self.progress

        # 2. 其次：根据关键成果计算
        kr_list = self.key_results.all()
        if kr_list:
            total_progress = sum(kr.progress for kr in kr_list)
            self.progress = round(total_progress / len(kr_list), 2)
            return self.progress

        # 3. 保持当前进度
        return self.progress

    def sync_to_subordinates(self, subordinate_ids):
        """同步目标到下属"""
        from app.models.user import User
        synced_objectives = []

        for user_id in subordinate_ids:
            user = User.query.get(user_id)
            if user:
                new_obj = Objective(
                    title=self.title,
                    description=self.description,
                    owner_id=user_id,
                    level='individual',
                    type=self.type,
                    parent_id=self.id,
                    start_date=self.start_date,
                    end_date=self.end_date
                )
                db.session.add(new_obj)
                synced_objectives.append(new_obj)

        return synced_objectives

    def to_dict(self, include_children=False):
        data = {
            'id': self.id,
            'title': self.title,
            'description': self.description,
            'owner_id': self.owner_id,
            'owner_name': self.owner.full_name if self.owner else None,
            'level': self.level,
            'type': self.type,
            'parent_id': self.parent_id,
            'start_date': self.start_date.isoformat() if self.start_date else None,
            'end_date': self.end_date.isoformat() if self.end_date else None,
            'progress': round(self.progress, 2),
            'status': self.status,
            'created_at': self.created_at.isoformat() if self.created_at else None,
            'key_results': [kr.to_dict() for kr in self.key_results.all()]
        }

        if include_children:
            data['children'] = [child.to_dict() for child in self.children.all()]

        return data


class KeyResult(db.Model):
    __tablename__ = 'key_results'

    id = db.Column(db.Integer, primary_key=True)
    objective_id = db.Column(db.Integer, db.ForeignKey('objectives.id'), nullable=False)
    title = db.Column(db.String(200), nullable=False)
    description = db.Column(db.Text)
    target_value = db.Column(db.Float, nullable=False)
    current_value = db.Column(db.Float, default=0.0)
    unit = db.Column(db.String(50))
    progress = db.Column(db.Float, default=0.0)
    status = db.Column(db.String(20), default='active')
    created_at = db.Column(db.DateTime, default=datetime.utcnow)
    updated_at = db.Column(db.DateTime, default=datetime.utcnow, onupdate=datetime.utcnow)

    # 关系
    progress_updates = db.relationship('ProgressUpdate', backref='key_result', lazy='dynamic')

    def update_progress(self):
        """更新进度百分比"""
        if self.target_value > 0:
            self.progress = min((self.current_value / self.target_value) * 100, 100)
        else:
            self.progress = 0
        return self.progress

    def to_dict(self):
        return {
            'id': self.id,
            'objective_id': self.objective_id,
            'title': self.title,
            'description': self.description,
            'target_value': self.target_value,
            'current_value': self.current_value,
            'unit': self.unit,
            'progress': round(self.progress, 2),
            'status': self.status,
            'created_at': self.created_at.isoformat() if self.created_at else None
        }